<script lang="ts">
import { useLocalStorage, useToggle } from '@peng_kai/kit/libs/vueuse';
import CloseBtn from '~/components/card/CloseBtn.vue';
import { useModalBindHash, useSyncToHashParams } from '~/composables/url';
import { getInvitationCode, icStorage } from '../helpers';
import { getBindGoogleProps } from './third-party/google/Google.vue';
import { useOneTap } from './third-party/google/useOneTap';
import { getTelegramAuthUrlParams } from './third-party/Telegram.vue';
import ThirdPartySign from './third-party/ThirdPartySign.vue';
import { useLoginApiMethods } from './third-party/useLoginApiMethods';

const viewMap = {
  signIn: {
    title: () => $t('qwZi820O3qWpsae62Juc'),
    comp: defineAsyncComponent(() => import('./SignIn.vue')),
  },
  signUp: {
    title: () => $t('wV2h5ZuzGb9WHcTjDAaGx'),
    comp: defineAsyncComponent(() => import('./SignUp.vue')),
  },
  forgetPassword: {
    title: () => $t('dj49WxBeDn3fRqBjRrqaB'),
    comp: defineAsyncComponent(() => import('../password/ForgetPassword.vue')),
  },
};

type ViewKeys = keyof typeof viewMap;

const DEF_VIEW_KEY: ViewKeys = 'signIn';

const viewNameRef = ref<ViewKeys>(DEF_VIEW_KEY);

function setViewNameRef(val: ViewKeys) {
  viewNameRef.value = val;
}

const getViewRef = computed(() => markRaw(viewMap[viewNameRef.value]));

const [pageLoading, setPageLoading] = useToggle(false);

export const signPopup = useAntdModal({
  // eslint-disable-next-line import/no-self-import
  is: defineAsyncComponent(() => import('./index.vue')),
  type: 'modal',
}, {
  wrapClassName: 'ant-cover__Modal ant-cover__Modal-sign',
  width: 'fit-content',
  centered: true,
  footer: null,
  maskClosable: false,
  opener() {
    setupIc(signPopup);
    if (!envs.isTg) {
      setupOneTap();
      setupWatchLoginMode(signPopup);
    }
  },
});

function setupIc(pop: ReturnType<typeof useAntdModal>) {
  const ic = getInvitationCode();
  ic && icStorage.set(ic);
  useModalBindHash({
    modalName: 'sign',
    requireAuth: false,
    isOpen: () => !!pop.modalProps.open,
    open(hashParams) {
      pop.open({ view: hashParams.get('view') as ViewKeys || DEF_VIEW_KEY });
    },
    close: pop.close,
  });
}

function setupOneTap() {
  const { googleOneTabLogin } = useLoginApiMethods();
  useOneTap({
    ...getBindGoogleProps(),
    onSuccess: (res) => {
      !envs.isTg && res?.credential && googleOneTabLogin({ credential: res.credential, referral_code: getInvitationCode() });
    },
    onError: () => window.console.error('Error with One Tap Login'),
  });
}

let watchErFunc: ReturnType<typeof watch> | null = null;

function setupWatchLoginMode(pop: ReturnType<typeof useAntdModal>) {
  const { confirmGoogleLogin, confirmTelegramLogin } = useLoginApiMethods(pop.close, void 0, setPageLoading);
  const { currentRoute, replace } = useRouter();

  watchErFunc?.();

  watchErFunc = watch(() => currentRoute.value.query, (query) => {
    if (envs.isTg) {
      return;
    }
    if (query?.code && query?.prompt && (query?.scope as string)?.indexOf?.('https://www.googleapis.com/auth/userinfo.email') > -1) {
      pop.open({ view: DEF_VIEW_KEY });
      confirmGoogleLogin({ code: String(query?.code) });
      replace({ query: {} });
      return;
    }

    const tgUrlRes = getTelegramAuthUrlParams();
    if (tgUrlRes?.id && tgUrlRes?.hash) {
      pop.open({ view: DEF_VIEW_KEY });
      confirmTelegramLogin(tgUrlRes);
    }
  }, { immediate: true });
  // /#tgAuthResult=eyJpZCI6NTg2NDg4MzQzNywiZmlyc3RfbmFtZSI6IkoiLCJsYXN0X25hbWUiOiJLIiwicGhvdG9fdXJsIjoiaHR0cHM6XC9cL3QubWVcL2lcL3VzZXJwaWNcLzMyMFwvaFZaRlotS01ocm5DSmdfV0ZLRnlMY2pzR2dkSEFuWjE2eE5yR2tRNWxaS3ZlUmgwdHI1NllOTW1QOTFNQ0ZaTi5qcGciLCJhdXRoX2RhdGUiOjE3Mjg1NTg1NjgsImhhc2giOiI2MDExM2NmODA1MWQyZTI5M2FlYmEyMTQwZmE2MTdlYTBjM2EzMWM4YzBhNGE1ODM4ODk4YjkxNGQzNjMyZWM0In0
}
</script>

<script setup lang="ts">
const props = defineProps<{ email?: string; view?: ViewKeys; onClose?: () => void }>();

props.view && setViewNameRef(props.view);
const luckyspinStorage = useLocalStorage<Record<string, any>>('firstGiveaway', {});

useSyncToHashParams({ view: { value: viewNameRef } });

function onBeforeClose() {
  if (luckyspinStorage.value?.firstDraw && !luckyspinStorage.value?.closed && props.view === 'signUp') {
    globalPopups.signUpForGiftingTipsPopup.open?.({ close: () => {
      props.onClose?.();
    } });
  }
  else {
    props.onClose?.();
  }
}
</script>

<template>
  <div
    class="sign-wrapper pointer-events-auto relative overflow-auto overscroll-none rounded-4"
    u:tablet="h-auto w-190 flex"
    u:lt-tablet=" w-100"
    u:lt-mobile="h-screen w-screen rounded-none bg-sys-layer-c"
  >
    <CloseBtn class="right-3 top-3 z-2 bg-sys-layer-c/30 backdrop-blur !absolute" @click="onBeforeClose" />

    <div v-if="$bp.tablet" class="relative min-h-160 flex-1 bg-sys-layer-d">
      <img src="./imgs/illus-pc2.png" class="block h-full w-full select-none object-cover">
      <div class="absolute bottom-4 left-8 right-8">
        <div class="text-center text-3xl text-sys-text-head font-800">
          WELCOME BONUS UP TO <span class="text-amber">590%</span>
        </div>
      </div>
    </div>
    <div v-else class="head-illus relative h-52 w-full bg-sys-layer-d">
      <img src="./imgs/illus-mobile2.png" class="block h-full w-full select-none object-cover">
      <div class="absolute left-4 top-1/2 w-70% -transform-translate-y-1/2">
        <div class="text-2xl text-sys-text-head font-700">
          WELCOME BONUS UP TO <span class="text-amber">590%</span>
        </div>
      </div>
    </div>

    <div
      class="min-h-115 flex flex-1 flex-col justify-between gap-3"
      u:tablet="p7 bg-sys-layer-c flex-1"
      u:lt-tablet="-mt-10 rounded-t-4 backdrop-blur p5 [background:linear-gradient(#1d1e2477,#1d1e24_10%)]"
    >
      <div>
        <div class="mb-3 text-lg font-600" u:tablet="mb-5 text-xl text-sys-text-head">
          {{ getViewRef.title() }}
        </div>
        <ASpin :spinning="pageLoading">
          <component
            :is="getViewRef.comp"
            :email="props.email"
            @toSignUp="setViewNameRef('signUp')"
            @toSignIn="setViewNameRef('signIn')"
            @toForgetPassword="setViewNameRef('forgetPassword')"
            @fulfilled="props.onClose"
          />
        </ASpin>
      </div>
      <ASpin v-if="!envs.isTg" :spinning="pageLoading" :indicator="h('span')">
        <ThirdPartySign class="mt-auto" :setLoading="setPageLoading" @fulfilled="props.onClose" />
      </ASpin>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:global(.ant-cover__Modal-sign .ant-modal) {
  max-width: none !important;

  @media bp-lt-mobile {
    --uno: 'absolute left-0 top-0 isolate';
  }
}

.head-illus {
  animation: rise 0.6s cubic-bezier(0.29, 0.67, 0.31, 1);

  @keyframes rise {
    0% {
      transform: translateY(100%);
      opacity: 0;
    }

    20% {
      opacity: 0;
    }

    100% {
      transform: translateY(0%);
      opacity: 1;
    }
  }
}
</style>
